﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using MySqlSugar;
using Zhj.Community.Domain.Entitys;
using Zhj.Community.Domain.IRepository;

namespace Zhj.Community.Repository
{
    public class BaseRepository<TEntity, TPrimaryKey> : IBaseRepository<TEntity, TPrimaryKey> where TEntity : BaseEntity<TPrimaryKey>, new()
    {
        public readonly string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

        public virtual  bool Add(TEntity T)
        {
            using (var db = new SqlSugarClient(ConnectionString))
            {
                return Convert.ToInt32(db.Insert(T)) > 0;
            }
        }

        public virtual bool Delete(TPrimaryKey id)
        {
            using (var db = new SqlSugarClient(ConnectionString))
            {
                return db.Delete<TEntity, TPrimaryKey>(id);
            }
        }

        public virtual bool Update(TEntity T)
        {
            using (var db = new SqlSugarClient(ConnectionString))
            {
                return db.Update(T);
            }
        }

        public virtual TEntity Get(TPrimaryKey id)
        {
            using (var db = new SqlSugarClient(ConnectionString))
            {
                return db.Queryable<TEntity>().Single(CreateEqualityExpressionForId(id));
            }
        }

        public virtual List<TEntity> Get(Expression<Func<TEntity, bool>> lmd)
        {
            using (var db = new SqlSugarClient(ConnectionString))
            {
                return db.Queryable<TEntity>().Where(lmd).ToList();
            }
        }

        public virtual List<TEntity> GetAll()
        {
            using (var db = new SqlSugarClient(ConnectionString))
            {
                return db.Queryable<TEntity>().ToList();
            }
        }

        protected static Expression<Func<TEntity, bool>> CreateEqualityExpressionForId(TPrimaryKey id)
        {
            var lambdaParam = Expression.Parameter(typeof(TEntity));
            var lambdaBody = Expression.Equal(
                Expression.PropertyOrField(lambdaParam, "Id"),
                Expression.Constant(id, typeof(TPrimaryKey))
                );
            return Expression.Lambda<Func<TEntity, bool>>(lambdaBody, lambdaParam);
        }
    }
}
